package com.zhang.ipertdemo

import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import com.zhang.ipertdemo.databinding.ActivityMainBinding
import java.io.BufferedReader
import java.io.File
import java.io.FileOutputStream
import java.io.InputStreamReader
import java.util.regex.Pattern


class MainActivity : AppCompatActivity() {
    private val TAG = "MainActivity"

    private lateinit var binding : ActivityMainBinding
    private val iperfPath by lazy {
        applicationContext.filesDir.absolutePath + File.separator + "iperf3"
    }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)
        initData()
    }

    private fun initData() {
        cloneIpert()
        binding.btnStart.setOnClickListener {
            runIpert()
        }
    }

    @Synchronized
    private fun cloneIpert() {
        val file = File(iperfPath)
        if (!file.exists()) {
            Log.d(TAG, "cloneIpert: ${file.path}")
//            Runtime.getRuntime().exec("chmod 777 " + file.absolutePath)
            resources.assets.open("iperf3").use {ins ->
                FileOutputStream(file).use { fos ->
                    val buffer = ByteArray(1024)
                    var len: Int
                    while (ins.read(buffer).also { len = it } != -1) {
                        fos.write(buffer, 0, len)
                    }
                }
            }
//            file.setReadable(true, false)
//            file.setWritable(true, false)
            file.setExecutable(true, false)
//            Runtime.getRuntime().exec("chmod 777 " + file.absolutePath).apply {
//                destroy()
//                Log.i(TAG, "the iperf file is ready")
//            }
        }

    }

    private val serverAdd = "192.168.169.100"
    private val serverPort = "17773"
    private  var iperfreply:String? = null


    private fun runIpert() {
        val iperfClientCmd = "$iperfPath -c $serverAdd -p $serverPort -t 10 -P 1"
//        val cmd = " -c $serverAdd -p $serverPort -t 10 -P 1"
        Log.d(TAG, "runIpert: $iperfClientCmd")
        val t = Thread {
            var errorreply = ""
            CommandHelper.DEFAULT_TIMEOUT = 150000
//            val result = CommandHelper.exec(iperfClientCmd)
//            b = new ProcessBuilder(new String[0]).command(strArr[0].split(" ")).redirectErrorStream(true).start();
            try {
                val b = ProcessBuilder().command(iperfClientCmd.split(" ")).redirectErrorStream(true).start()
                val bufferedReader = BufferedReader(InputStreamReader(b.inputStream))
                while (true) {
                    val readLine = bufferedReader.readLine() ?: break
                    Log.i(TAG, "$readLine.trimIndent()")
//                    publishProgress("$readLine".trimIndent())
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }

//            if (result != null) {
//                //start to connect the service
//                if (result.error != null) {
////                    errorreply = result.error
////                    val m = Message()
////                    m.obj = errorreply
////                    m.what = 1
////                    handler.sendMessage(m)
//                    Log.i(TAG, "Error:$errorreply")
//                }
//                if (result.output != null) {
//                    iperfreply = getThroughput(result.output)
////                    IPERF_OK = true
////                    val m = Message()
////                    m.obj = iperfreply
////                    m.what = 2
//////                    handler.sendMessage(m)
//                    Log.i(TAG, "Output:$iperfreply")
//                }
//                Log.i(TAG, "result.getExitValue(): " + result.exitValue)
//            }
        }
        t.start()
    }

    /**
     * 从获取到的吞吐量信息中截取需要的信息，如：
     * 0.0-10.0 sec  27.5 MBytes  23.0 Mbits/sec
     */
    private fun getThroughput(str: String): String? {
        val regx = "0.0-.+?/sec"
        var result = ""
        val matcher = Pattern.compile(regx).matcher(str)
        Log.i(TAG, "matcher regx : " + regx + " is " + matcher.matches())
        if (matcher.find()) {
            Log.i(TAG, "group: " + matcher.group())
            result = matcher.group()
        }
        return result
    }
}